package com.iflytek.jzcpx.procuracy.web.card.controller;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSONObject;
import com.iflytek.jzcpx.procuracy.card.component.CardFormFieldRemark;
import com.iflytek.jzcpx.procuracy.card.entity.CardFile;
import com.iflytek.jzcpx.procuracy.card.entity.CardFormField;
import com.iflytek.jzcpx.procuracy.card.pojo.ElleFileInHandleParam;
import com.iflytek.jzcpx.procuracy.card.pojo.ElleFullParam;
import com.iflytek.jzcpx.procuracy.card.pojo.ElleImgInAcceptParam;
import com.iflytek.jzcpx.procuracy.card.pojo.ElleInFolderParam;
import com.iflytek.jzcpx.procuracy.card.pojo.ElleOuterInHandleParam;
import com.iflytek.jzcpx.procuracy.card.pojo.ElleOuterSyncInHandleParam;
import com.iflytek.jzcpx.procuracy.card.pojo.ElleWordInAcceptParam;
import com.iflytek.jzcpx.procuracy.common.result.Result;
import com.iflytek.jzcpx.procuracy.web.card.bd.CardBDService;
import com.iflytek.jzcpx.procuracy.web.card.vo.FieldSourceParamVO;
import com.iflytek.jzcpx.procuracy.web.card.vo.FieldSourceVO;
import com.iflytek.jzcpx.procuracy.web.config.MetricInterface;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.collections4.MapUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

/**
 * 案卡接口
 *
 * @author <a href=mailto:ktyi@iflytek.com>伊开堂</a>
 * @date 2019-08-06 19:52
 */
@Api(value = "案卡", tags = "案卡")
@RestController
@RequestMapping("/api/card")
public class CardController {
    private static final Logger logger = LoggerFactory.getLogger(CardController.class);

    @Autowired
    private CardBDService cardBDService;

    @ApiOperation("案件受理成功, 更新受理阶段的文件编码对应的部门受案号到数据库")
    @PostMapping("/accept/bmsah")
    public Result bmsah(@RequestBody String reqBody) {
        logger.info("案件受理成功, 接收更新文件编码对应的部门受案号消息. content: {}", reqBody);
        // todo 更新受理阶段文件编码对应的部门受案号到数据库
        /*
         {
            "bmsah": "汉东省院起诉受[2019]77000000034号",  #部门受案号
            "wjbm": "NFDEHFIUDSCMDSJCNSDJFNW"      #文件MD5值
        }
        */
        CardFile cardFile=JSONObject.parseObject(reqBody, CardFile.class);
        String bmsah=cardFile.getBmsah();
        String wjbm=cardFile.getWjbm();
        boolean b=this.cardBDService.updateBmsahByWjbm(wjbm, bmsah);
        if(b) {
        	return Result.success();
        }
        return Result.failed("更新失败！");
    }

    @ApiOperation(value = "受理阶段高拍文件案卡提取")
    @PostMapping("/accept/img")
    @MetricInterface(stringVal = "受理阶段高拍文件案卡提取")
    public Result<JSONObject> acceptImg(HttpServletRequest request, @RequestParam("wdwjl") MultipartFile[] files) {
        ElleImgInAcceptParam imgExtractParam = new ElleImgInAcceptParam();
        imgExtractParam.setAjlbbm(request.getParameter("ajlbbm"));
        imgExtractParam.setWjbm(request.getParameter("wjbm"));
        imgExtractParam.setWslx(request.getParameter("wslx"));
        imgExtractParam.setWjlx(request.getParameter("wjlx"));
        logger.info("受理阶段高拍文件案卡提取(不打印bdjg字段), param: {}", imgExtractParam);
        imgExtractParam.setBdjg(request.getParameter("bdjg"));

        List<byte[]> wdwjl = new ArrayList<>();
        for (MultipartFile file : files) {
            try (InputStream is = file.getInputStream()) {
                JSONObject jsonObj = JSONObject.parseObject(is, StandardCharsets.UTF_8, JSONObject.class);
                //String fileName = jsonObj.getString("name");
                //String format = jsonObj.getString("format");

                byte[] bytes = Base64.decodeBase64(jsonObj.getString("base64"));
                wdwjl.add(bytes);
            }
            catch (IOException e) {
                logger.warn("解析上传图片发生异常.", e);
            }
        }
        imgExtractParam.setWdwjl(wdwjl);
        return cardBDService.extractBase64ImgInAccept(imgExtractParam);
    }

    @ApiOperation(value = "受理阶段文书文件案卡提取")
    @PostMapping("/accept/file")
    @MetricInterface(stringVal = "受理阶段文书文件案卡提取")
    public Result<JSONObject> acceptFile(HttpServletRequest request, @RequestParam("wdwjl") MultipartFile file) {
        ElleWordInAcceptParam wordExtractParam = new ElleWordInAcceptParam();
        wordExtractParam.setAjlbbm(request.getParameter("ajlbbm"));
        wordExtractParam.setWjbm(request.getParameter("wjbm"));
        wordExtractParam.setWslx(request.getParameter("wslx"));
        wordExtractParam.setWjlx(request.getParameter("wjlx"));
        logger.info("受理阶段文书文件案卡提取(不打印bdjg字段)， param: {}", wordExtractParam);
        wordExtractParam.setBdjg(request.getParameter("bdjg"));
        try {
            wordExtractParam.setWdwjl(file.getBytes());
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        return cardBDService.extractWordInAccept(wordExtractParam);
    }

    @ApiOperation(value = "办理文书案卡提取-同步")
    @PostMapping("/handle/file")
    @MetricInterface(stringVal = "办理文书案卡提取-同步")
    public Result<JSONObject> handleFile(@RequestBody String reqBody) {
        ElleFileInHandleParam logObj = JSONObject.parseObject(reqBody, ElleFileInHandleParam.class);
        logObj.setBdjg(null);
        logObj.setWswj(null);
        logger.info("办理文书案卡提取， param: {}", logObj);

        ElleFileInHandleParam elleFileInHandleParam = JSONObject.parseObject(reqBody, ElleFileInHandleParam.class);
        return cardBDService.extractFileInHandle(elleFileInHandleParam);
    }


    @ApiOperation(value = "入卷后批量案卡提取-异步")
    @PostMapping("/handle/rj")
    @MetricInterface(stringVal = "入卷后批量案卡提取-异步")
    public Result inFolder(@RequestBody ElleInFolderParam elleInFolderParam) {
        logger.info("入卷后批量案卡提取， param: {}", elleInFolderParam);
        return cardBDService.inFolder(elleInFolderParam);
    }

    @ApiOperation(value = "外来文书案卡提取-同步")
    @PostMapping("/handle/outer/sync")
    @MetricInterface(stringVal = "外来文书案卡提取-同步")
    public Result<JSONObject> handleOuterSync(@RequestBody String reqBody) {
        ElleOuterSyncInHandleParam logObj = JSONObject.parseObject(reqBody, ElleOuterSyncInHandleParam.class);
        logObj.setBdjg(null);
        logObj.setJzwswj(null);
        logger.info("外来文书案卡提取-同步， param: {}", logObj);

        ElleOuterSyncInHandleParam elleOuterSyncInHandleParam = JSONObject.parseObject(reqBody, ElleOuterSyncInHandleParam.class);
        return cardBDService.handleOuterSync(elleOuterSyncInHandleParam);
    }

    @ApiOperation(value = "外来文书案卡提取-异步")
    @PostMapping("/handle/outer/async")
    @MetricInterface(stringVal = "外来文书案卡提取-异步")
    public Result handleOuterAsync(@RequestBody ElleOuterInHandleParam elleOuterInHandleParam) {
        logger.info("外来文书案卡提取-异步， param: {}", elleOuterInHandleParam);
        return cardBDService.handleOuterAsync(elleOuterInHandleParam);
    }

    @ApiOperation(value = "全案卡提取")
    @PostMapping("/handle/full")
    @MetricInterface(stringVal = "全案卡提取")
    public Result<JSONObject> handleFull(@RequestBody String reqBody) {
        ElleFullParam logObj = JSONObject.parseObject(reqBody, ElleFullParam.class);
        logObj.setBdjg(null);
        logger.info("全案卡提取， param: {}", logObj);

        ElleFullParam elleFullParam = JSONObject.parseObject(reqBody, ElleFullParam.class);
        return cardBDService.handlFull(elleFullParam);
    }

    @ApiOperation(value = "差异化页面字段数据")
    @PostMapping("/handle/full/source")
    public Result<List<FieldSourceVO>> fieldSourcePage(@RequestBody FieldSourceParamVO paramVO) {
        String stbm = paramVO.getStbm();
        String stzd = paramVO.getStzd();
        String id = URLDecoder.decode(new String(Base64.decodeBase64(paramVO.getId())));

        String ajxx = paramVO.getAjxx();
        byte[] bytes = Base64.decodeBase64(ajxx);
        JSONObject ajxxJson = JSONObject.parseObject(URLDecoder.decode(new String(bytes)), JSONObject.class);
        String bmsah = ajxxJson.getString("bmsah");

        Map<CardFile, List<CardFormField>> cardFileAndFormFields = cardBDService.listFieldsForDiff(bmsah, stbm, stzd, id);
        if (MapUtils.isEmpty(cardFileAndFormFields)) {
            return Result.success();
        }

        List<FieldSourceVO> vos = new ArrayList<>();
        for (Map.Entry<CardFile, List<CardFormField>> entry : cardFileAndFormFields.entrySet()) {
            CardFile cardFile = entry.getKey();
            List<CardFormField> formFieldList = entry.getValue();
            for (CardFormField cardFormField : formFieldList) {
                FieldSourceVO vo = new FieldSourceVO();
                vo.setFileName(cardFile.getWsmc());
                vo.setFileContent(cardFile.getFileContent());
                vo.setValue(cardFormField.getZdwbz());
                CardFormFieldRemark remark = CardFormFieldRemark.fromRemark(cardFormField.getRemark());
                if (remark != null) {
                    vo.setStartPosition(remark.getBeginPosition());
                    vo.setEndPosition(remark.getEndPisiton());
                }
                vos.add(vo);
            }
        }

        return Result.success(vos);
    }
}
